package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mobeta.android.dslv.DragSortListView;
import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.SceneActionDragSortListViewAdapter;
import cn.innosmart.aq.bean.ActionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.SceneBean;
import cn.innosmart.aq.customize.PrioritySetDialog;
import cn.innosmart.aq.manager.SceneManager;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/8/20.
 */
public class SceneActivity extends BaseActivity {
    public static SceneBean sceneBean;
    private final int EXIT = 0;
    private final int ADDSCENE = 1;
    private final int MODIFYSCENE = 2;
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private ArrayList<String> actions;
    private AquariumBean aquariumBean;
    private TextView tvAddInfo;
    private DragSortListView dslvAction;
    private SceneActionDragSortListViewAdapter sceneActionDragSortListViewAdapter;
    private ConnectionEntity connectionEntity;
    private EditText etSceneName;
    private String sceneId;
    private TextView tvPriority;
    //监听器在手机拖动停下的时候触发
    private DragSortListView.DropListener onDrop =
            new DragSortListView.DropListener() {
                @Override
                public void drop(int from, int to) {//from to 分别表示 被拖动控件原位置 和目标位置
                    if (from != to) {
                        ActionBean item = (ActionBean) sceneActionDragSortListViewAdapter.getItem(from);//得到listview的适配器
                        sceneActionDragSortListViewAdapter.remove(from);//在适配器中”原位置“的数据。
                        sceneActionDragSortListViewAdapter.insert(item, to);//在目标位置中插入被拖动的控件。
                    }
                }
            };
    //删除监听器，点击左边差号就触发。删除item操作。
    private DragSortListView.RemoveListener onRemove =
            new DragSortListView.RemoveListener() {
                @Override
                public void remove(int which) {
                    sceneActionDragSortListViewAdapter.remove(which);
                }
            };
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case EXIT:
                    //退出
                    exit();
                    break;
                case ADDSCENE:
                    //添加场景
                    loadingDialog();
                    SceneManager.getInstance().Add(connectionEntity, sceneBean.toParams(), new SceneManager.AddCallBack() {
                        @Override
                        public void onAddResponseCallBack(int ret, String id) {
                            if (ret == 0) {
                                sceneBean.setId(id);
                                aquariumBean.getSceneList().add(sceneBean);
                                hideloadingDialog();
                                exit();
                            }
                        }
                    });
                    break;
                case MODIFYSCENE:
                    //修改场景
                    loadingDialog();
                    //发送更新指令
                    SceneManager.getInstance().Update(connectionEntity, sceneBean.toParams(), new SceneManager.UpdateCallBack() {
                        @Override
                        public void onUpdateResponseCallBack(int ret, String id) {
                            if (ret == 0) {
                                for (int i = 0; i < aquariumBean.getSceneList().size(); i++) {
                                    SceneBean oldsceneBean = (SceneBean) aquariumBean.getSceneList().get(i);
                                    if (id.equals(oldsceneBean.getId())) {
                                        aquariumBean.getSceneList().remove(i);
                                        aquariumBean.getSceneList().add(sceneBean);
                                        hideloadingDialog();
                                        exit();
                                    }
                                }
                            }
                        }
                    });
                    break;
            }
        }
    };
    private Menu menus;
    private CheckBox cbPushMessage;
    private int position = -1;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.scene_add_action:
                    //添加ACtion
                    Intent intent = new Intent(SceneActivity.this, AddActionActivity.class);
                    intent.putExtra("flag", "scene");
                    intent.putStringArrayListExtra("actions", actions);
                    startActivity(intent);
                    break;
                case R.id.add_scene:
                    //添加场景
                    String sceneName = etSceneName.getText().toString().trim();
                    if (!TextUtils.isEmpty(sceneName)) {
                        sceneBean.setTitle(sceneName);
                        sceneBean.setIconName("ic_scene");
                        if (sceneBean.getCommands() == null || sceneBean.getCommands().size() == 0) {
                            showToast(getString(R.string.activity_scene_action_can_not_empty));
                        } else {
                            if (sceneId == null) {
                                if (checkRepeatTitle(sceneName)) {
                                    showToast(getString(R.string.name_can_not_empty));
                                    break;
                                }
                                mHandler.sendEmptyMessage(ADDSCENE);
                            } else {
                                if (checkRepeatTitle(sceneName)) {
                                    showToast(getString(R.string.name_had_used));
                                    break;
                                }
                                mHandler.sendEmptyMessage(MODIFYSCENE);
                            }
                        }
                    } else {
                        showToast(getString(R.string.name_can_not_empty));
                    }
                    break;
            }
            return true;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scene);
        aquariumBean = SystemConstant.currentAquariumBean;
        sceneId = getIntent().getStringExtra("scene");
        setBar(sceneId);
        initPosition();
        tvAddInfo = (TextView) findViewById(R.id.tv_add_info);
        actions = new ArrayList<String>();
        actions.addAll((ArrayList<String>) aquariumBean.getActionDevices().clone());
        assignView();
        assignData(sceneId);
        assignListview();
    }

    //初始化控件
    private void assignListview() {
        sceneActionDragSortListViewAdapter = new SceneActionDragSortListViewAdapter(this, sceneBean.getCommands());
        dslvAction.setRemoveListener(onRemove);
        dslvAction.setDropListener(onDrop);
        dslvAction.setAdapter(sceneActionDragSortListViewAdapter);
        dslvAction.setDragEnabled(true);
        connectionEntity = ConnectionManager.getInstance().getCurrentConnectionEntity();
        cbPushMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sceneBean.setPns("pns");
                } else {
                    sceneBean.setPns(null);
                }
            }
        });
    }

    /**
     * 根据sceneID判断是否为空 填充数据
     *
     * @param sceneId
     */
    private void assignData(String sceneId) {
        sceneBean = new SceneBean();
        sceneBean.setPlace(aquariumBean.getId());
        sceneBean.pns_priority = 1;
        if (sceneId != null) {
            ArrayList<ActionBean> commands = new ArrayList<ActionBean>();
            for (int i = 0; i < aquariumBean.getSceneList().size(); i++) {
                SceneBean sceneBeans = (SceneBean) aquariumBean.getSceneList().get(i);
                if (sceneId.equals(sceneBeans.getId())) {
                    sceneBean.setId(new String(sceneBeans.getId()));
                    sceneBean.setTitle(new String(sceneBeans.getTitle()));
                    sceneBean.setIconName(new String(sceneBeans.getIconName()));
                    sceneBean.setPns(sceneBeans.getPns() == null ? null : new String(sceneBeans.getPns()));
                    sceneBean.pns_priority = sceneBeans.pns_priority;
                    commands.addAll(sceneBeans.getCommands());
                    sceneBean.setCommands(commands);
                    sceneBean.setPlace(new String(sceneBeans.getPlace()));
                    break;
                }
            }
        } else {
            sceneBean.setPns("pns");
            cbPushMessage.setChecked(true);
        }
        String pns = sceneBean.getPns();
        if (pns == null) {
            cbPushMessage.setChecked(false);
        } else if (pns.equals("pns")) {
            cbPushMessage.setChecked(true);
        }
        if (sceneId == null) {
            cbPushMessage.setChecked(true);
        }
        tvPriority.setText(priorityStrIds[sceneBean.pns_priority]);
        tvPriority.setTag(sceneBean.pns_priority);
    }

    /**
     * 初始化自定义控件
     */
    private void assignView() {
        tvPriority = (TextView) findViewById(R.id.tv_priority);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriorityWindow(tvPriority);
            }
        });
        cbPushMessage = (CheckBox) findViewById(R.id.cb_push_message);
        dslvAction = (DragSortListView) findViewById(R.id.dslv_action);
        etSceneName = (EditText) findViewById(R.id.et_scene_name);
    }

    private void setBar(String sceneId) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        if (sceneId == null) {
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_add_scene));
        } else {
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_modify_scene));
        }

        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_scene, menu);
        menus = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onResume() {
        if (sceneBean.getCommands() != null)
            sceneActionDragSortListViewAdapter.update(sceneBean.getCommands());
        if (sceneBean.getCommands() == null || sceneBean.getCommands().size() == 0) {
            tvAddInfo.setVisibility(View.VISIBLE);
        } else {
            tvAddInfo.setVisibility(View.GONE);
        }
        if (sceneId != null)
            etSceneName.setText(sceneBean.getTitle());
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void initPosition() {
        if (sceneId != null && aquariumBean.getSceneList() != null) {
            for (int i = 0; i < aquariumBean.getSceneList().size(); i++) {
                SceneBean sceneBean = (SceneBean) aquariumBean.getSceneList().get(i);
                if (sceneBean.getId().equals(sceneId)) {
                    position = i;
                }
            }
        }
    }

    /**
     * 检查重复标题
     * @param title
     * @return
     */
    private boolean checkRepeatTitle(String title) {
        if (sceneId == null && aquariumBean.getSceneList() != null) {
            for (Object object : aquariumBean.getSceneList()) {
                if (title.equals(((SceneBean) object).getTitle())) {
                    return true;
                }
            }
        } else if (sceneId != null && aquariumBean.getSceneList() != null) {
            for (int i = 0; i < aquariumBean.getSceneList().size(); i++) {
                if (title.equals(((SceneBean) aquariumBean.getSceneList().get(i)).getTitle())) {
                    if (i == position) {
                        continue;
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //----
    //----
    //
    //----
    //----

    /**
     * 显示优先级对话框
     * @param tvPriority
     */
    private void showPriorityWindow(final TextView tvPriority) {
        final PrioritySetDialog priorityDialog = new PrioritySetDialog(this, (Integer) tvPriority.getTag());
        priorityDialog.setTitle(getString(R.string.alarm_priority_title));
        priorityDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.dismiss();
            }
        });
        priorityDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.checkChange();
            }
        });
        priorityDialog.setOnChangeListener(new PrioritySetDialog.OnChangeListener() {
            @Override
            public void onChange(int type) {
                switch (type) {
                    case 1:
                        if (checkPushStatus()) {
                            priorityDialog.dismiss();
                            tvPriority.setText(getString(priorityStrIds[type]));
                            tvPriority.setTag(type);
                            sceneBean.pns_priority = type;
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 2:
//                        checkPushAndSmsStatus();
                        if (checkPushStatus()) {
                            if (checkSmsStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                sceneBean.pns_priority = type;
                            } else {
                                //跳转到SMS界面
                                switchToSmsActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 3:
                        if (checkPushStatus()) {
                            if (checkTelStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                sceneBean.pns_priority = type;
                            } else {
                                //跳转到Tel界面
                                switchToTelActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                }
            }
        });
        priorityDialog.setCanceledOnTouchOutside(true);
        priorityDialog.show();
    }

    private void switchToTelActivity() {
        Intent intent = new Intent(this, TelPushMessageActivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToSmsActivity() {
        Intent intent = new Intent(this, SmsPushMessageActivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToPushActivity() {
        Intent intent = new Intent(this, PushMessageSettingAcitivity.class);
        startActivityForResult(intent, 1);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private boolean checkTelStatus() {
        if (SharedUtil.getInstance().readTelStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkSmsStatus() {
        if (SharedUtil.getInstance().readSmsStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkPushStatus() {
        if (SharedUtil.getInstance().readXinStatus(connectionEntity.getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }
}
